package com.carHailing.common.handler;
import com.alibaba.fastjson.JSONObject;
import com.carHailing.common.exception.BizException;
import com.carHailing.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.stream.Collectors;

/**
 * @author DongZl
 * @description: 全局异常处理
 * @Date 2024-1-10 下午 08:49
 */
@RestControllerAdvice
@Configuration
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result<String> runtimeException (MethodArgumentNotValidException exception) {
        return Result.error(
                JSONObject.toJSONString(
                        exception.getBindingResult().getAllErrors()
                                .stream()
                                .map(ObjectError::getDefaultMessage)
                                .collect(Collectors.toList())
                )
        );
    }

    @ExceptionHandler(value = IllegalArgumentException.class)
    public Result<String> illegalArgumentExceptionHandler(IllegalArgumentException exception) {
        log.error("请求异常：[{}]", exception.getMessage(), exception);
        return Result.error(exception.getMessage());
    }

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(BizException.class)
    public Result handleRRException(BizException e){
        return Result.error(e.getCode(),e.getMessage());
    }



    @ExceptionHandler(DuplicateKeyException.class)
    public Result handleDuplicateKeyException(DuplicateKeyException e){
        log.error(e.getMessage(), e);
        return Result.error("数据库中已存在该记录");
    }


    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e){
        log.error(e.getMessage(), e);
        return Result.error();
    }











}
